import { createSlice } from '@reduxjs/toolkit';

// 模拟初始数据
const initialState = {
  statistics: {
    totalUsers: 0,
    newUsers: 0,
    totalCourses: 0,
    activeUsers: 0,
    activeRate: 0,
    totalRevenue: 0,
    revenueGrowth: 0
  },
  courseData: {
    salesTrend: [],
    courses: []
  },
  userData: {
    activityData: [],
    retentionRate: 0
  },
  announcements: [],
  loading: false,
  error: null
};

const adminSlice = createSlice({
  name: 'admin',
  initialState,
  reducers: {
    setDashboardData: (state, action) => {
      return { ...state, ...action.payload };
    },
    setLoading: (state, action) => {
      state.loading = action.payload;
    },
    setError: (state, action) => {
      state.error = action.payload;
    },
    addAnnouncement: (state, action) => {
      state.announcements.unshift(action.payload);
    },
    updateAnnouncement: (state, action) => {
      const index = state.announcements.findIndex(a => a.id === action.payload.id);
      if (index !== -1) {
        state.announcements[index] = action.payload;
      } else {
        state.announcements.unshift(action.payload);
      }
    }
  }
});

export const {
  setDashboardData,
  setLoading,
  setError,
  addAnnouncement,
  updateAnnouncement
} = adminSlice.actions;

// 异步 action creator
export const fetchDashboardData = (timeRange) => async (dispatch) => {
  try {
    dispatch(setLoading(true));
    // 模拟 API 调用
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 模拟数据
    const mockData = {
      statistics: {
        totalUsers: 1000,
        newUsers: 50,
        totalCourses: 100,
        activeUsers: 500,
        activeRate: 50,
        totalRevenue: 100000,
        revenueGrowth: 15
      },
      courseData: {
        salesTrend: Array.from({ length: 7 }, (_, i) => ({
          date: new Date(Date.now() - i * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          sales: Math.floor(Math.random() * 100) + 50
        })).reverse(),
        courses: [
          {
            id: 1,
            title: 'React 基础教程',
            studentCount: 500,
            completionRate: 75,
            rating: 4.5
          },
          // ... 可以添加更多模拟数据
        ]
      },
      userData: {
        activityData: Array.from({ length: 7 }, (_, i) => ({
          date: new Date(Date.now() - i * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          activeUsers: Math.floor(Math.random() * 300) + 200
        })).reverse(),
        retentionRate: 65
      }
    };

    dispatch(setDashboardData(mockData));
  } catch (error) {
    dispatch(setError(error.message));
  } finally {
    dispatch(setLoading(false));
  }
};

export default adminSlice.reducer; 